<template>
  <div class="chat-list">
    <div class="chat-list-header">
      <h3>聊天列表</h3>
      <el-button type="primary" icon="el-icon-plus" @click="showCreateGroup">创建群聊</el-button>
    </div>
    <div class="chat-list-content">
      <el-menu
        :default-active="activeChat ? activeChat.groupId.toString() : ''"
        @select="handleSelect"
      >
        <el-menu-item
          v-for="chat in chatList"
          :key="chat.groupId"
          :index="chat.groupId.toString()"
        >
          <div class="chat-item">
            <div class="chat-info">
              <div class="chat-name">{{ chat.groupName }}</div>
              <div class="chat-last-message">
                <template v-if="chat.messages && chat.messages.length > 0">
                  <span class="sender-name">{{ getSenderName(chat.messages[0]) }}: </span>
                  {{ chat.messages[0].content }}
                </template>
                <template v-else>
                  暂无消息
                </template>
              </div>
            </div>
            <div class="chat-time" v-if="chat.messages && chat.messages.length > 0">
              {{ formatTime(chat.messages[0].createdAt) }}
            </div>
          </div>
        </el-menu-item>
      </el-menu>
    </div>
    <create-group ref="createGroup" @created="handleGroupCreated" />
  </div>
</template>

<script>
import { getUserGroups } from '@/api/chat'
import CreateGroup from './create-group.vue'

export default {
  name: 'ChatList',
  components: {
    CreateGroup
  },
  data() {
    return {
      chatList: [],
      activeChat: null
    }
  },
  created() {
    this.loadChatList()
  },
  methods: {
    async loadChatList() {
      try {
        const response = await getUserGroups()
        if (response.code === 20000) {
          this.chatList = response.data
        }
      } catch (error) {
        console.error('加载聊天列表失败:', error)
        this.$message.error('加载聊天列表失败')
      }
    },
    handleSelect(index) {
      const chat = this.chatList.find(c => c.groupId.toString() === index)
      if (chat) {
        this.activeChat = chat
        this.$emit('select', chat)
      }
    },
    showCreateGroup() {
      this.$refs.createGroup.show()
    },
    handleGroupCreated(group) {
      this.loadChatList()
      this.$message.success('群组创建成功')
    },
    getSenderName(message) {
      if (!message || !message.user) return '未知用户'
      return message.user.name || message.user.userName || '未知用户'
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      // 如果是今天的消息，只显示时间
      if (diff < 24 * 60 * 60 * 1000) {
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 如果是昨天的消息
      if (diff < 48 * 60 * 60 * 1000) {
        return '昨天'
      }
      
      // 其他显示日期
      return `${date.getMonth() + 1}/${date.getDate()}`
    }
  }
}
</script>

<style scoped>
.chat-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e6e6e6;
}

.chat-list-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6e6e6;
}

.chat-list-header h3 {
  margin: 0;
}

.chat-list-content {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.chat-info {
  flex: 1;
  margin-right: 10px;
  overflow: hidden;
}

.chat-name {
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-last-message {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sender-name {
  color: #409EFF;
  font-weight: 500;
}

.chat-time {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.el-menu {
  border-right: none;
}

.el-menu-item {
  height: auto;
  line-height: 1.5;
  padding: 10px 20px;
}
</style>